from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger


from app.fault_self_recovery.models.fsr_host_disk import FSRHostDisk


class FSRHostDiskHandler():
    """  HostDate Handler
    """
    def __init__(self):
        pass


    def get_host_disk_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取服务器磁盘列表信息
        """
        try:
            field_info = {field: value}
            order_info = {"classes": "asc", "name": "asc"}
            result = FSRHostDisk.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.error(f"get host disk search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get host disk search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result




    def get_host_disk_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取服务器列表信息
        """
        try:
            result = FSRHostDisk.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.error(f"get host disk match, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get host disk match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result




    def add_host_disk(self, db: Session, data: dict):
        """
        创建服务器磁盘信息
        """
        try:
            host_disk_object = FSRHostDisk.get_object_by_ip_mountpoint(db, data["ip"], data["mountpoint"])
            if host_disk_object:
                # 如果ip地址和挂载目录存在， 则异常返回
                logger.error(f"add host disk failed, ip:{data['ip']} mountpoint:{data['mountpoint']}  was exist")
                return False

            result = FSRHostDisk.add(db, data)
            if not result:
                logger.error(f"add host disk to database failed")
                return False
        except Exception as e:
            message = f"add host disk error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def update_host_disk(self, db: Session, data: dict):
        """
        修改服务器磁盘信息
        """
        try:
            host_disk_object = FSRHostDisk.get_object_by_uuid(db, data['uuid'])
            if not host_disk_object:
                # 如果不存在， 则异常返回
                logger.error(f"update host disk failed, uuid:{data['uuid']} not exist")
                return False

            host_disk_object = FSRHostDisk.get_object_by_ip_mountpoint(db, data["ip"], data["mountpoint"])
            if host_disk_object and host_disk_object.uuid != data['uuid']:
                # 如果ip地址和挂载目录存在， 则异常返回
                logger.error(f"update host disk failed, ip:{data['ip']} mountpoint:{data['mountpoint']}  was exist")
                return False

            # 更新服务器磁盘信息
            result = FSRHostDisk.update(db, data)
            if not result:
                logger.error(f"update host disk to database failed")
                return False
        except Exception as e:
            message = f"update host disk error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def delete_host_disk(self, db: Session, data: dict):
        """
        删除服务器磁盘信息
        """
        try:
            host_disk_object = FSRHostDisk.get_object_by_uuid(db, data['uuid'])
            if not host_disk_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete host disk failed, uuid:{data['uuid']} not exist")
                return False

            # 删除服务器磁盘信息
            FSRHostDisk.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete host disk error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True

